import random
import re
import string
# pip install opencv-python
# pip install pillow
from datetime import datetime
from urllib.parse import urlencode


# 根据字典替换文字
def replace_chars_by_dit(text, dictionary):
    for key, value in dictionary.items():
        text = text.replace(key, value)
    return text


# 获取选择器属性
def identify_selector_type(selector):
    if re.match(r'^#[\w-]+$', selector):
        return 'id'
    elif re.match(r'^[.\w-]+[\w-]*$', selector):
        return 'css'
    elif re.match(r'^(//.*|\(//.*|\*\[contains\(.*\)\]|\*\[@id=\'.*\'\])', selector):
        return 'xpath'
    elif re.match(r'^<[\w-]+>$', selector):
        return 'tag'
    elif re.match(r'^<a.*>.*</a>$', selector):
        return 'link'
    elif re.match(r'.*<a.*>.*</a>.*', selector):
        return 'partial link'
    elif re.match(r'^\[name=[\'\"].*[\'\"]\]$', selector):
        return 'name'
    elif re.match(r'^\[class=[\'\"].*[\'\"]\]$', selector):
        return 'class'
    else:
        return 'unknown'


# 获取选择器内容
def extract_value_from_selector(selector):
    match = re.match(r'^#([\w-]+)$', selector)
    if match:
        return match.group(1)

    match = re.match(r'^\.([\w-]+[\w-]*)$', selector)
    if match:
        return match.group(1)

    match = re.match(r'^(//.*|\(//.*|\*\[contains\((.*)\)\]|\*\[@id=\'(.*)\'\])', selector)
    if match:
        return match.group(1)

    match = re.match(r'^<([\w-]+)>$', selector)
    if match:
        return match.group(1)

    match = re.match(r'^<a.*>(.*)</a>$', selector)
    if match:
        return match.group(1)

    match = re.match(r'.*<a.*>(.*)</a>.*', selector)
    if match:
        return match.group(1)

    match = re.match(r'^\[name=[\'\"](.*)[\'\"]\]$', selector)
    if match:
        return match.group(1)

    match = re.match(r'^\[class=[\'\"](.*)[\'\"]\]$', selector)
    if match:
        return match.group(1)

    return None


# 判断是否可调用
def is_function(f):
    return callable(f)


# 判断一个对象是否是字符串
def is_string(o):
    return isinstance(o, str)


def get_timestamp():
    """
    获取当前时间的时间戳（秒数）

    :return: 当前时间的时间戳
    """
    return int(datetime.now().timestamp())


def format_time_difference(timestamp_start, timestamp_end):
    """
    计算两个时间戳之间的时间差，并格式化为人类可读的时间格式

    :param timestamp_start: 起始时间戳
    :param timestamp_end: 结束时间戳
    :return: 格式化的时间差字符串
    """
    # 将时间戳转换为 datetime 对象
    start_time = datetime.utcfromtimestamp(timestamp_start)
    end_time = datetime.utcfromtimestamp(timestamp_end)

    # 计算时间差
    time_difference = end_time - start_time

    # 提取各个部分
    days = time_difference.days
    hours, remainder = divmod(time_difference.seconds, 3600)
    minutes, seconds = divmod(remainder, 60)

    # 构建格式化字符串
    formatted_parts = []
    if days > 0:
        formatted_parts.append("{:02}天".format(days))
    if hours > 0 or (days == 0 and hours == 0):
        formatted_parts.append("{:02}小时".format(hours))
    if minutes > 0 or (days == 0 and hours == 0 and minutes == 0):
        formatted_parts.append("{:02}分钟".format(minutes))
    formatted_parts.append("{:02}秒".format(seconds))

    # 将各个部分连接起来
    formatted_time = " ".join(formatted_parts)

    return formatted_time


# 将超过指定长度的字符串截断，并在末尾添加省略号（'……'）
def ellipsize(s, max_length):
    if len(s) <= max_length:
        return s

    max_length = max_length - 2
    truncated = s[:max_length]

    # 如果最后一个字符是代理字符，需要检查是否截断了代理对
    if 0xd800 <= ord(truncated[max_length - 1]) <= 0xdbff and \
            0xdc00 <= ord(s[max_length]) <= 0xdfff:
        truncated = s[:max_length + 1]

    return truncated + '……'


# 函数遍历输入的文件名字符串，将无效字符替换为下划线，并返回安全的文件名。
def safe_file_name(name):
    INVALID_FILE_NAME_CHARS = set('"<>|\0\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\v\f\r\u000e\u000f' +
                                  '\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f' +
                                  ':*?\\/')

    safe_name = ''
    for ch in name:
        if ch in INVALID_FILE_NAME_CHARS:
            safe_name += '_'
        else:
            safe_name += ch
    return safe_name


# 接受一个字典作为输入，并返回一个URL编码的查询字符串
def obj_to_query_string(obj):
    if not obj:
        return ''

    query_params = []
    for key, value in obj.items():
        if isinstance(value, list):
            for item in value:
                query_params.append((key, item))
        else:
            query_params.append((key, value))

    return urlencode(query_params)


def safe_file_name(name, max_length=255):
    INVALID_FILE_NAME_CHARS = set('"<>|\0\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\v\f\r\u000e\u000f'
                                  + '\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f'
                                  + ':*?\\/')

    safe_name = ''
    for ch in name:
        if ch in INVALID_FILE_NAME_CHARS:
            safe_name += '_'
        else:
            safe_name += ch

    # 截取文件名的前 max_length 个字符
    safe_name = safe_name[:max_length]

    return safe_name


def generate_realistic_username():
    """
    生成贴近真人的用户名

    :return: 生成的用户名
    """
    # 一些常见姓氏和名字的首字母
    surnames = ["Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller"]
    first_names = ["Emma", "Liam", "Olivia", "Noah", "Ava", "Sophia", "Jackson"]

    # 随机选择姓氏和名字
    surname = random.choice(surnames)
    first_name = random.choice(first_names)

    # 生成用户名，例如：jsmith123
    username = f"{first_name.lower()}{surname.lower()}{random.randint(100, 999)}"

    return username


def generate_random_password(length=12):
    """
    生成随机密码

    :param length: 密码长度，默认为 12
    :return: 生成的密码
    """
    characters = string.ascii_letters + string.digits + string.punctuation
    random_password = ''.join(random.choice(characters) for _ in range(length))
    return random_password


def generate_random_email():
    """
    生成随机邮箱

    :return: 生成的邮箱
    """
    # 随机生成用户名
    username = generate_random_username()

    # 随机选择一个常见的邮箱域名
    domain = random.choice(["gmail.com", "yahoo.com", "hotmail.com", "example.com", "domain.com"])

    # 组合生成邮箱地址
    email = f"{username}@{domain}"

    return email


def generate_random_username(length=8):
    """
    生成随机用户名

    :param length: 用户名长度，默认为 8
    :return: 生成的用户名
    """
    characters = string.ascii_letters + string.digits
    username = ''.join(random.choice(characters) for _ in range(length))
    return username


def generate_random_last_name():
    """
    生成随机姓氏

    :return: 生成的姓氏
    """
    last_names = ["Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore", "Taylor"]

    # 随机选择一个姓氏
    last_name = random.choice(last_names)

    return last_name


def generate_random_first_name():
    """
    生成随机名字

    :return: 生成的名字
    """
    first_names = ["Emma", "Liam", "Olivia", "Noah", "Ava", "Sophia", "Jackson", "Isabella", "Lucas", "Mia"]

    # 随机选择一个名字
    first_name = random.choice(first_names)

    return first_name


if __name__ == "__main__":
    print(identify_selector_type('#my-id'))  # Outputs: id
    print(identify_selector_type('.my-class'))  # Outputs: css
    print(identify_selector_type('//div[@id="my-id"]'))  # Outputs: xpath
    print(identify_selector_type('<div>'))  # Outputs: tag
    print(identify_selector_type('<a href="my-link.html">My Link</a>'))  # Outputs: link
    print(identify_selector_type('Some text <a href="my-link.html">My Link</a> some text'))  # Outputs: partial link
    print(identify_selector_type('[name="my-name"]'))  # Outputs: name
    print(identify_selector_type('[class="my-class"]'))  # Outputs: class

    print(extract_value_from_selector('#my-id'))  # Outputs: ('id', 'my-id')
    print(extract_value_from_selector('.my-class'))  # Outputs: ('css', 'my-class')
    print(extract_value_from_selector('//div[@id="my-id"]'))  # Outputs: ('xpath', '//div[@id="my-id"]')
    print(extract_value_from_selector('<div>'))  # Outputs: ('tag', 'div')
    print(extract_value_from_selector('<a href="my-link.html">My Link</a>'))  # Outputs: ('link', 'My Link')
    print(extract_value_from_selector(
        'Some text <a href="my-link.html">My Link</a> some text'))  # Outputs: ('partial link', 'My Link')
    print(extract_value_from_selector('[name="my-name"]'))  # Outputs: ('name', 'my-name')
    print(extract_value_from_selector('[class="my-class"]'))

    # 示例用法
    timestamp_start = 1639713600  # 起始时间戳
    timestamp_end = 1639724400  # 结束时间戳

    formatted_time = format_time_difference(timestamp_start, timestamp_end)
    print(f"Time Difference: {formatted_time}")

    random_and_meaningful_username = generate_realistic_username()
    print(f"Random and Meaningful Username: {random_and_meaningful_username}")

    random_password = generate_random_password()
    print(f"Random Password: {random_password}")

    random_email = generate_random_email()
    print(f"Random Email: {random_email}")

    random_last_name = generate_random_last_name()
    print(f"Random Last Name: {random_last_name}")

    random_first_name = generate_random_first_name()
    print(f"Random First Name: {random_first_name}")